package com.GithubMeizhis.adapter;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.GithubMeizhis.MyMeizhiFactory;
import com.GithubMeizhis.R;
import com.GithubMeizhis.entity.Gank;
import com.GithubMeizhis.entity.GankData;
import com.GithubMeizhis.util.AXLog;
import com.GithubMeizhis.util.LoveStrings;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

import static android.text.style.TtsSpan.ARG_DAY;
import static android.text.style.TtsSpan.ARG_MONTH;
import static android.text.style.TtsSpan.ARG_YEAR;

/**
 * Created by Administrator on 2017/9/18.
 */
public class GankFragmentMY extends Fragment {

    @Bind(R.id.list)
    RecyclerView list;
    @Bind(R.id.video_image)
    ImageView videoImage;
    @Bind(R.id.collapsing_toolbar)
    CollapsingToolbarLayout collapsingToolbar;
    @Bind(R.id.content_layout)
    CoordinatorLayout contentLayout;

    List<Gank> mGankList = new ArrayList<Gank>();
    private int mYear,mMonth,mDay;
    private String mVideoPreviewUrl;

    public static GankFragmentMY newInstance(int year, int month, int day) {
        AXLog.e("wzytest","run in GankFragmentMY newInstance");
        GankFragmentMY fragment = new GankFragmentMY();
        Bundle args = new Bundle();
        args.putInt(ARG_YEAR, year);
        args.putInt(ARG_MONTH, month);
        args.putInt(ARG_DAY, day);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        parseArguments();
        loadGankDta();

    }

    private void parseArguments() {
        Bundle bundle = getArguments();
        mYear = bundle.getInt(ARG_YEAR);
        mMonth = bundle.getInt(ARG_MONTH);
        mDay = bundle.getInt(ARG_DAY);
    }

    private void getOldVideoPreview(OkHttpClient client) {
        String url = "http://gank.io/" + String.format("%s/%s/%s", mYear, mMonth, mDay);
        Request request = new Request.Builder().url(url).build();
        AXLog.e("wzytest","request:"+request.body() +":"+request.url());
        client.newCall(request).enqueue(new Callback() {
            @Override public void onFailure(Call call, IOException e) {

                e.printStackTrace();
            }


            @Override public void onResponse(Call call, Response response) throws IOException {
                String body = response.body().string();
//                AXLog.e("wzytest","body:"+body);
                mVideoPreviewUrl = LoveStrings.getVideoPreviewImageUrl(body);
                startPreview(mVideoPreviewUrl);
            }
        });
    }

    private void startPreview(String preview) {

        mVideoPreviewUrl = preview;


        if (preview != null && videoImage != null) {
//            videoImage.post(() ->
                    Glide.with(videoImage.getContext())
                            .load(preview)
                            .into(videoImage);
//            );

        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_gank, container, false);
        ButterKnife.bind(this, rootView);
        list.setLayoutManager(new LinearLayoutManager(getActivity()));
        list.setAdapter(new GankListAdapter(mGankList));
        getOldVideoPreview(new OkHttpClient());
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.list, R.id.video_image, R.id.collapsing_toolbar, R.id.content_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.list:
                break;
            case R.id.video_image:
                break;
            case R.id.collapsing_toolbar:
                break;
            case R.id.content_layout:
                break;
        }
    }
    private List<Gank> addAllResults(GankData.Result results) {
        if (results.androidList != null) mGankList.addAll(results.androidList);
        if (results.iOSList != null) mGankList.addAll(results.iOSList);
        if (results.appList != null) mGankList.addAll(results.appList);
        if (results.拓展资源List != null) mGankList.addAll(results.拓展资源List);
        if (results.瞎推荐List != null) mGankList.addAll(results.瞎推荐List);
        if (results.休息视频List != null) mGankList.addAll(0, results.休息视频List);
        AXLog.e("wzytest","results:"+mGankList.size() );
        return mGankList;
    }

    public void loadGankDta(){
        MyMeizhiFactory.getsGankIOSingleton().getGankData(mYear,mMonth,mDay)
//                .map(gankData -> gankData.results)
                .map(new Func1<GankData, GankData.Result>() {
                    @Override
                    public GankData.Result call(GankData gankData) {
                        AXLog.e("wzytest","gankdata:"+gankData);
                        return gankData.results;
                    }
                })
                .map( result -> addAllResults(result))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(

                        new Observer<List<Gank>>() {
                            @Override
                            public void onCompleted() {
                                AXLog.e("wzytest","run in onCompleted");
                            }

                            @Override
                            public void onError(Throwable e) {
                                AXLog.e("wzytest","run in onError");
                            }

                            @Override
                            public void onNext(List<Gank> ganks) {
                                AXLog.e("wzytest","run in onNext" );
                                list.getAdapter().notifyDataSetChanged();
                            }
                        }
                );
    }
}
